// pages/order/order.js
var api = require("../../utils/api.js");
var util = require("../../utils/util.js");
//获取应用实例
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // invoice_col:true,  //发票弹窗
    controlDome: true, //地址弹窗
    // invoiceSwitch:'0',  //发票开关
    addressSwitch: '0',
    taxpayers: true,
    hasGroup:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      windowHeight: app.globalData.windowHeight
    })

    if (options.shopId) {
      this.setData({
        shopId: options.shopId
      })
      // this.authorization();
    }

  },
  onShow: function () {
    this.authorization();
    util.showLoading("加载中...");
    this.setData({
      "invoice_col": true,
      "controlDome": true
    })
  },

  //地址请求
  addressList: function () {
    var params = new Object()
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'address/list',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            address: res.data.data.address_list
          })
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  },


  //购物车请求
  cartList: function () {
    var params = new Object()
    var that = this;
    var carNum = 0;
    var total = 0;
    params.shop_id = this.data.shopId
    // params.tokken = app.globalData.accountInfo.token
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/goodsList',
      success: function (res) {

        util.hiddenLoading();

        if (util.isEmpty(res.data.code)) {
          
          if (res.data.data.hasGroup==1){
            that.setData({
              hasGroup:true
            })
          }else{
            that.setData({
              hasGroup: false
            })
          }

          var carts = res.data.data.list

          if (carts.length > 0) {
            for (var i = 0; i < carts.length; i++) {
              carts[i].total = (carts[i].num * carts[i].vip_price).toFixed(2);
              total += carts[i].num * (carts[i].vip_price >= 0 ? carts[i].vip_price : 0);
              carNum += carts[i].num / 1;
            }
          }
          that.setData({
            carts: res.data.data.list,
            total: total.toFixed(2)
          })
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  },

  invoiceColShow: function () {
    this.setData({
      "invoice_col": false
    })
  },
  invoiceColHide: function () {
    this.setData({
      "invoice_col": true
    })
  },

  controlDomeShow: function () {
    this.setData({
      "controlDome": false
    })
  },
  controlDomeHide: function () {
    this.setData({
      "controlDome": true
    })
  },
  addressColShow:function(){
    var that = this;
    wx.showActionSheet({
      itemList: ['不需要配送', '需要配送'],
      success: function (res) {
        // console.log(res.tapIndex)
        if (res.tapIndex==0){
          that.setData({
            addressSwitch: '0'
          })
        } else if (res.tapIndex == 1){
          that.setData({
            addressSwitch: '1'
          })
        }
        
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  taxpayersCol: function () {
    var taxpayers = this.data.taxpayers;
    if (taxpayers) {
      this.setData({
        taxpayers: false
      })
    } else {
      this.setData({
        taxpayers: true
      })
    }
  },

  //发票开关
  invoiceSwitch: function (e) {
    // console.log(e);
    if (e.detail.value == true) {
      this.setData({
        invoiceSwitch: 1
      })
    } else {
      this.setData({
        invoiceSwitch: 0
      })
    }
  },

  invoiceClick: function (e) {
    // console.log(e.currentTarget.dataset.col);
    var col = e.currentTarget.dataset.col;
    this.setData({
      invoiceSwitch: col
    })
  },

  radioChange: function (e) {
    var id = e.detail.value
    var that = this;
    var list = that.data.address;
    for (var i = 0; i < list.length; i++) {
      // console.log(list[i].aid);
      if (list[i].aid == id) {
        var params = {
          aid: id,
          username: list[i].username,
          mobile: list[i].mobile,
          province: list[i].province.name,
          town: list[i].town.name,
          city: list[i].city.name,
          address: list[i].address,
          is_default: 1,
          street: list[i].street.name
        }
        // console.log(params);
        api.POST({
          params: params,
          url: app.globalData.base_url + 'address/modify',
          success: function (res) {
            if (util.isEmpty(res.data.code)) {
              that.addressList();
              that.setData({
                "controlDome": true
              })
            }
          },
          fail: function (fail) {
            util.showError("登录失败，请检查网络");

          }
        })

      }
    }
  },

  //输入发票抬头
  invoice_title: function (e) {
    this.setData({
      invoiceTitle: e.detail.value
    })
  },

  //输入发票税号
  invoice_number: function (e) {
    this.setData({
      invoiceNumber: e.detail.value
    })
  },

  //修改地址
  editorAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/addAddress/addAddress?aid=' + id
    })
  },
  //删除地址
  deleteAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    api.POST({
      params: { aid: id },
      url: app.globalData.base_url + 'address/del',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          util.showStatus("删除成功")
          that.addressList();
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  },

  // 支付订单
  payOrder: function () {
    var params = new Object()
    var that = this;
    var list = [];
    params.record = [];
    util.showLoading("加载中");
    for (var i = 0; i < this.data.carts.length; i++) {
      var box = {};
      box.sku_code = this.data.carts[i].sku_code
      box.num = this.data.carts[i].num
      list.push(box);
    }
    params.record = JSON.stringify(list)
    // console.log(list);
    params.shop_id = this.data.shopId
    // console.log(this.data.invoiceSwitch);

    // if (this.data.invoiceSwitch == '1') {
    //   params.invoice = '个人'
    // } else if (this.data.invoiceSwitch == 2) {

    //   params.invoice = this.data.invoiceTitle
    //   params.invoice_number = this.data.invoiceNumber
    //   if (this.data.invoiceTitle != undefined && this.data.invoiceTitle != '') {
    //     params.invoice = this.data.invoiceTitle
    //   } else {
    //     util.showError("抬头不能为空");
    //     return false;
    //   }

    //   if (this.data.invoiceNumber != undefined && this.data.invoiceNumber != '') {
    //     params.invoice = this.data.invoiceNumber
    //   } else {
    //     util.showError("请输入税号");
    //     return false;
    //   }
    // }

    if (this.data.addressSwitch == '1') {
      var address = this.data.address
      for (var i = 0; i < address.length; i++) {
        if (address[i].is_default == 1) {
          params.aid = address[i].aid
        }
      }

      if (params.aid == undefined || params.aid == '') {
        util.showError("请选择收货地址");
        return false;
      }
    }
    // params = JSON.stringify(params)
    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/submit',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          that.orderInfo(res.data.data.result.oid);
          that.wxPayOrder(res.data.data.result.oid);
        } else if (res.data.code=="2499"){
          util.showError("库存不足");
        } else {
          // console.log(res.data);
          // util.showError(res.data.message);
          util.showError("库存不足");
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  },

  //订单信息
  orderInfo: function (oid) {
    var that = this;
    api.POST({
      params: { oid: oid },
      url: app.globalData.orderInfo_url,
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          wx.setStorageSync('orderData', res.data.data)
        }
      }
    })

  },


  //支付接口
  wxPayOrder: function (oid) {
    var params = new Object()
    var that = this;
    params.oid = oid;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {


          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              wx.redirectTo({
                url: '../paySuccess/paySuccess?oid=' + oid
              })
            },
            fail: function (error) {
              util.showError("支付失败");
              wx.removeStorageSync('orderData');
              setTimeout(function () {
                wx.redirectTo({
                  url: '../orderList/orderList'
                })
              }, 1000)
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },


  // 授权
  authorization: function () {
    var that = this
    wx.login({
      success: function (res_login) {
        wx.getUserInfo({
          withCredentials: true,
          success: function (res_user) {
            var login_code = res_login.code;
            var login_encryptedData = res_user.encryptedData;
            var login_iv = res_user.iv;
            that.autoLogin(login_code, login_encryptedData, login_iv);
          }, fail: function (fail_user) {
            that.showModal();
          }
        })
      }, fail: function (fail_login) {
        console.log("fail");
      }
    })
  },

  // 重新授权
  reAuthorization: function () {
    var that = this
    wx.openSetting({
      success: function (res) {
        if (res.authSetting["scope.userInfo"]) {
          that.authorization();
        }
      }
    })
  },

  //未登录警告框
  showModal: function () {
    var that = this
    wx.showModal({
      title: '警告',
      content: '若不授权登录，则无法使用',
      confirmText: '授权',
      cancelText: '不授权',
      success: function (suress) {
        if (suress.confirm) {
          that.reAuthorization();
        } else {
          that.showModal();
        }
      }
    })
  },

  //登录请求
  autoLogin: function (login_code, login_encryptedData, login_iv) {
    var that = this;
    var params = new Object()
    params.code = login_code;
    params.encryptedData = login_encryptedData;
    params.iv = login_iv;

    api.POST({
      params: params,
      url: app.globalData.base_url + 'user/login',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          app.globalData.accountInfo = res.data.data.result;
          that.addressList();
          that.cartList();
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  }
})